<?php
namespace App\Admin\Controllers\Car;

use App\Models\Car;
use App\Models\CarBrand;
use Dcat\Admin\Controllers\AdminController;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;

class BrandController extends AdminController
{
    public $title = '汽车品牌管理';


    /**
     * 列表
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new CarBrand());
        $grid->id->sortable();
        $grid->column('pinyin_first', '首字母')->sortable();
        $grid->name;

        $grid->filter(function (Grid\Filter $filter){
            $filter->equal('pinyin_first', '首字母');
            $filter->like('name', '名称');
        });

        return $grid;
    }


    /**
     * 表单
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new CarBrand());
        $form->display('id');
        $form->text('name')->required()->rules(function (Form $form){
            $rules  = 'max:20|unique:car_brand,name';
            $id     = $form->model()->id;
            $rules .= ",{$id},id";
            $rules .= ',deleted_at,NULL';

            return $rules;
        });

        return $form;
    }


    /**
     * 详情
     * @param $id
     * @return Show
     */
    protected function detail($id)
    {

        $show = new Show($id, new CarBrand());
        $show->id;
        $show->name;

        return $show;
    }


    /**
     * 删除
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {

        $is_exists_car = Car::query()->whereIn('brand_id', explode(',', $id))->count();
        if($is_exists_car)
            return response()->json(['status'=> false, 'message'=> '删除失败，该品牌下存在车辆']);

        return parent::destroy($id);

    }
}
